package com.example.administrator.xxnapp.login;

import com.example.administrator.xxnapp.bean.UserBean;
import com.example.administrator.xxnapp.fragment.mine.IModelMine;
import com.example.administrator.xxnapp.http.CustomStringCallback;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;

/**
 * Created by Went_Gone on 2018/5/8.
 */

public class UserPresenter {
    private IViewUser mIView;
    private IModelMine mIModel;

    public UserPresenter(IViewUser mIView, IModelMine mIModel) {
        this.mIView = mIView;
        this.mIModel = mIModel;
    }

    public void signIn(String phoneNum,String password){
        mIModel.signIn(phoneNum,password).execute(new CustomStringCallback() {
            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                mIView.loginError("无法连接，请稍后重试~");
            }

            @Override
            public void onSuccessString(Gson gson, String responseBody) {
                try {
                    JSONObject object = new JSONObject(responseBody);
                    if (object.getInt("result") == 200){
                        Type type = new TypeToken<UserBean>() {
                        }.getType();
                        UserBean bean = gson.fromJson(object.getJSONObject("data").toString(),type);
                        mIView.loginSuccess(bean);
                    }else {
                        mIView.loginError(object.getString("data"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
